<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>欢迎回来，{{ userStore.user?.full_name }}管理员</h1>
      <p>今天是{{ currentDate }}，祝您工作愉快！</p>
    </div>

    <div class="dashboard-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#409EFF">
                <User />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalUsers }}</div>
                <div class="stat-label">总用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#67C23A">
                <UserFilled />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalStudents }}</div>
                <div class="stat-label">学生数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#E6A23C">
                <Avatar />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalTeachers }}</div>
                <div class="stat-label">教师数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <el-icon class="stat-icon" size="32" color="#F56C6C">
                <Document />
              </el-icon>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalExams }}</div>
                <div class="stat-label">总考试数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="dashboard-content">
      <el-row :gutter="20">
        <el-col :span="16">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>系统概览</span>
                <el-button type="primary" @click="$router.push('/users')">
                  用户管理
                </el-button>
              </div>
            </template>
            <el-table :data="recentUsers" style="width: 100%" v-loading="loading">
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="full_name" label="姓名" />
              <el-table-column prop="email" label="邮箱" />
              <el-table-column prop="role" label="角色" width="100">
                <template #default="{ row }">
                  <el-tag :type="getRoleType(row.role)">
                    {{ getRoleText(row.role) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="created_at" label="注册时间" width="180">
                <template #default="{ row }">
                  {{ formatDateTime(row.created_at) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleEditUser(row)"
                  >
                    编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>快捷操作</span>
              </div>
            </template>
            <div class="quick-actions">
              <el-button 
                type="primary" 
                size="large" 
                @click="$router.push('/users')"
                style="width: 100%; margin-bottom: 10px;"
              >
                <el-icon><User /></el-icon>
                用户管理
              </el-button>
              <el-button 
                type="success" 
                size="large" 
                @click="$router.push('/exams')"
                style="width: 100%; margin-bottom: 10px;"
              >
                <el-icon><Document /></el-icon>
                考试管理
              </el-button>
              <el-button 
                type="warning" 
                size="large" 
                @click="$router.push('/logs')"
                style="width: 100%; margin-bottom: 10px;"
              >
                <el-icon><List /></el-icon>
                日志查看
              </el-button>
              <el-button 
                type="info" 
                size="large" 
                @click="handleViewStats"
                style="width: 100%;"
              >
                <el-icon><DataLine /></el-icon>
                数据统计
              </el-button>
            </div>
          </el-card>

          <el-card style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>系统状态</span>
              </div>
            </template>
            <div class="system-status">
              <div class="status-item">
                <div class="status-label">系统运行状态</div>
                <el-tag type="success">正常</el-tag>
              </div>
              <div class="status-item">
                <div class="status-label">数据库连接</div>
                <el-tag type="success">正常</el-tag>
              </div>
              <div class="status-item">
                <div class="status-label">API服务</div>
                <el-tag type="success">正常</el-tag>
              </div>
              <div class="status-item">
                <div class="status-label">最后更新</div>
                <div class="status-time">{{ lastUpdate }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import api from '../api'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { User, UserFilled, Avatar, Document, List, DataLine } from '@element-plus/icons-vue'

const userStore = useUserStore()
const router = useRouter()

const loading = ref(false)
const users = ref([])
const exams = ref([])

const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const lastUpdate = computed(() => {
  return new Date().toLocaleString('zh-CN')
})

const stats = computed(() => {
  const totalUsers = users.value?.length || 0
  const totalStudents = users.value?.filter(user => user.role === 'student').length || 0
  const totalTeachers = users.value?.filter(user => user.role === 'teacher').length || 0
  const totalExams = exams.value?.length || 0

  return {
    totalUsers,
    totalStudents,
    totalTeachers,
    totalExams
  }
})

const recentUsers = computed(() => {
  return users.value?.slice(0, 5) || []
})

const loadData = async () => {
  loading.value = true
  try {
    const [usersRes, examsRes] = await Promise.all([
      api.users.getUsers({ limit: 100 }),
      api.exams.getExams({ limit: 100 })
    ])
    users.value = usersRes.data
    exams.value = examsRes.data.items
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (datetime) => {
  return new Date(datetime).toLocaleString('zh-CN')
}

const getRoleType = (role) => {
  const roleMap = {
    'admin': 'danger',
    'teacher': 'warning',
    'student': 'success'
  }
  return roleMap[role] || 'info'
}

const getRoleText = (role) => {
  const roleMap = {
    'admin': '管理员',
    'teacher': '教师',
    'student': '学生'
  }
  return roleMap[role] || '未知'
}

const handleEditUser = (user) => {
  router.push(`/user/${user.id}`)
}

const handleViewStats = () => {
  router.push('/statistics')
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.dashboard-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.dashboard-stats {
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 16px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.system-status {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

.status-time {
  font-size: 12px;
  color: #909399;
}
</style>